package com.study;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;

/**
 * @author Mayjean
 * @Date2020/10/8
 */
public class MyClassLoader extends ClassLoader{


    private String classPath;
    public MyClassLoader(String classPath){
        super(ClassLoader.getSystemClassLoader());
        this.classPath = classPath;
    }


    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        byte[] bytes = this.loadClassData(name);
        return this.defineClass(name,bytes,0,bytes.length);
    }

    private byte[] loadClassData(String name) {
        try{
            name = name.replace(".","//");
            FileInputStream fis = new FileInputStream(classPath+name+".class");
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            int b;
            while ((b = fis.read()) != -1){
                baos.write(b);
            }
            fis.close();
            return baos.toByteArray();
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }
}